package process

import (
	"github.com/influxdata/influxdb-client-go/v2/api/query"
	"math"
	"notifications/pkg/influx"
	"notifications/pkg/modals"
)

// SupportLine is the struct for support line
func SupportLine(line *modals.SupportLine, name string, record *query.FluxRecord) modals.SupportLine {
	line.Name = name
	switch record.Measurement() {
	case "away":
		line.Away = record.Value().(float64)
	case "busy":
		line.Busy = record.Value().(float64)
	case "online":
		line.Online = record.Value().(float64)
	case "conversations-opened-assigned":
		line.ConvOpenedAss = record.Value().(float64)
	case "conversations-opened-unassigned":
		line.ConvOpenedUnass = record.Value().(float64)
	case "conversations-awaiting-assigned":
		line.ConvAwaitAss = record.Value().(float64)
	case "conversations-awaiting-unassigned":
		line.ConvAwaitUnass = record.Value().(float64)
	case "conversations-solved-assigned":
		line.ConvSolvedAss = record.Value().(float64)
	case "conversations-solved-unassigned":
		line.ConvSolvedUnass = record.Value().(float64)
	}
	return *line
}

// ResultInfluxDB is the struct for result
func ResultInfluxDB() modals.AllLine {
	var results = influx.ClientInfluxDB()
	var allLine = modals.AllLine{
		SupportLine: make([]modals.SupportLine, 4),
	}
	for results.Next() {
		lineName := results.Record().ValueByKey("line").(string)
		switch lineName {
		case "1 линия поддержки":
			SupportLine(&allLine.SupportLine[0], lineName, results.Record())
		case "2 линия поддержки":
			SupportLine(&allLine.SupportLine[1], lineName, results.Record())
		case "Опоздания":
			SupportLine(&allLine.SupportLine[2], lineName, results.Record())
		case "Качество и Сборка":
			SupportLine(&allLine.SupportLine[3], lineName, results.Record())
		}
	}
	return allLine
}

// CalculateAllValues calculates all values
func CalculateAllValues(line modals.SupportLine) (int, int, int) {
	line.AllAss = int(math.Ceil(line.ConvOpenedAss + line.ConvSolvedAss + line.ConvAwaitAss))
	line.AllUnass = int(math.Ceil(line.ConvOpenedUnass + line.ConvAwaitUnass + line.ConvSolvedUnass))
	line.All = line.AllAss + line.AllUnass
	return line.All, line.AllAss, line.AllUnass
}

// Calc calculates
func Calc(allLine *modals.AllLine) {
	for i := range allLine.SupportLine {
		allLine.SupportLine[i].All, allLine.SupportLine[i].AllAss, allLine.SupportLine[i].AllUnass = CalculateAllValues(allLine.SupportLine[i])
	}
}
